"""
启用无头浏览器模式

如何破解针对Selenium的反爬措施
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)

browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
})
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

# 通过ChromeOptions对象可以指定启动浏览器时用到的参数
options = webdriver.ChromeOptions()
# options.add_argument('--headless')
# 关掉浏览器窗口上方显示的"Chrome正受到自动测试软件的控制"
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)
browser = webdriver.Chrome(options=options)
# 执行Chrome开发者协议（CDP）命令在加载新页面时执行指定的JavaScript代码
browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
})
# 设置浏览器窗口的尺寸
browser.set_window_size(1280, 960)
browser.get('https://www.baidu.com')
browser.implicitly_wait(10)
kw_input = browser.find_element_by_css_selector('#kw')
kw_input.send_keys('骆昊')
kw_input.send_keys(Keys.ENTER)
# 使用显示等待的方式等到搜索结果加载出来 ---> #\31
wait = WebDriverWait(browser, 10)
# 通过WebDriverWait对象的until方法设置等待的期望条件
wait.until(expected_conditions.presence_of_element_located(
    (By.CSS_SELECTOR, 'div.result')
))
# 为浏览器窗口生成一个快照并保存成图片文件
browser.get_screenshot_as_file('results.png')
# browser.close()
# print('程序结束！！！')
